/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2024-11-08 11:17:48
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2024-11-08 11:43:06
 * @FilePath: /zhuang/sharemem/Fifo.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <unistd.h>
#include <fcntl.h>
using namespace std;

const string gpipefile = "./fifo"; // 公共文件
const mode_t gPipemode = 0600;
const int gdeafultfd = -1; // 默认fd
const int gsize = 1024;    // 默认缓冲区大小

const int gForRead = O_RDONLY;
const int gForWrite = O_WRONLY;

class Fifo
{

private:
    void OpenFifo(int flag)
    {
        _fd = ::open(gpipefile.c_str(), flag);
        if (_fd < 0)
        {
            cerr << "open fail" << endl;
        }
    }

public:
    Fifo() : _fd(-1)
    {
        umask(0);
        int n = ::mkfifo(gpipefile.c_str(), gPipemode);
        if (n < 0) // 创建失败
        {
          //  cerr << "mkfifo error" << endl;
            return;
        }
        cout << "mkfifo success" << endl;
    }

    bool OpenPipeForWrite()
    {
        OpenFifo(gForWrite);
        if (_fd < 0)
            return false;
        return true;
    }

    bool OpenPipeForRead()
    {
        OpenFifo(gForRead);
        if (_fd < 0)
            return false;
        return true;
    }
    // 读
    int Wait()
    {
        int code = 0;

        ssize_t n = ::read(_fd, &code, sizeof(code));
        // 我们将数据当成字符串
        if (n == sizeof(code))
        {
            return 0;
        }
        else if (n == 0) // 退出
        {
            return 1;
        }
        else
            return 2;
    }

    void Signal()
    {
        int code = 1;
        ::write(_fd, &code, sizeof(code));
    }

    ~Fifo()
    {
        if (_fd >= 0)
            ::close(_fd);
        int n = unlink(gpipefile.c_str());
        if (n < 0)
        {
            cerr << "unlink error" << endl;
            return;
        }
        cout << "unlink success" << endl;
    }

private:
    int _fd;
};

Fifo gpipe;